# -*- coding: utf8 -*-
# brackets.py

import os, re, time
from core.ircfuncs import irc_lower, access_idx
from util.pywikilib import Time, WikiLink
from util.functions import convert_bytes, encode, capitalize
from random import randint, choice

from util.functions import *

"""
Function attributes:
* load: boolean. Optional. If False the function will not load.
* name: string. Optional.
* priority: string. Optional. Three values are available: "high", "medium" or "low", default value: "medium".
* thread: boolean. Optional. If True, function will work by starting a thread.
* rule: string or regexp object. Requered.
* aliases: list of string or regexp objects. Optional.
* sentence: boolean. Optional. If True, pattern is searched on whole message, else pattern is a command, it begins
  the msg with a sign.
"""

def brackets(bot, evt, cmd):
	"""Wikilinks. It returns an url link from a wikilink. You can use [[X]] to redirect to a page or {{X}} to a template, it accepts lang codes and some prefixes. More: $more"""
	if not bot.channels[evt.chan].links: return True
	links = re.finditer(ur"(?P<whole>(?P<pref>[\w\-:]+|[\\!dcfhjlLnrRt])*(?P<link>(?:\{\{|\[\[)(?:[^\]}]+)(?:\}\}|\]\])))", evt.msg)
	loop = 0; mxm = 5 if access_idx(bot, "support", evt) else 3
	rtn=[]
	for m in links:
		if re.search(r"!(?:\[\[|\{\{)", m.group("whole")): continue
		if loop == mxm: break
		done = re.search(r"(?<!\\)\{\{([Dd]one|[Ff]et|[Hh]echo)\}\}", m.group("whole"))
		if done:
			done = done.group(1).lower()
			if  done == "done":
				bot.reply(evt, u"How efficient, $nick!")
				continue
			elif done == "fet":
				bot.reply(evt, u"Què eficient eres, $nick!")
				continue
			elif done == "hecho":
				bot.reply(evt, u"¡Qué eficiente eres, $nick!")
				continue
		wlink = WikiLink(m.group("whole"), evt.lang, evt.fam)
		url = wlink.url()
		extra = ""
		if m.group("pref"):
			if "t" in  m.group("pref"):
				info = wlink.info()
				size = convert_bytes(info['size'])
				if size == "0 B":
					url = ""
				else:
					redir = "&o;(%s)&N;" % bot._translate(evt, "redirect") if info.has_key("redirect") else ""
					extra = " %s. %s%s. %s%s. %s." % (
						redir,
						bot._translate(evt, "&B;Size:&N; "),
						size,
						bot._translate(evt, "&B;Last edit:&N; "),
						Time(info['touched']).to_simple_string(),
						bot._translate(evt, "&B;Served in:&N; %s secs") % (info['delay'],),
					)
		if url:
			if not brackets.stack.has_key(evt.chan):
				brackets.stack[evt.chan] = [url]
				#rtn.append(u"&t;[%i]&N; %s%s" %(1, url, extra))
				bot.pub_msg(evt, u"&t;[%i]&N; %s%s", 1, url, extra)
			elif url not in brackets.stack[evt.chan]:
				brackets.stack[evt.chan].append(url)
				#rtn.append(u"&t;[%i]&N; %s%s" %(len(brackets.stack[evt.chan]), url, extra))
				bot.pub_msg(evt, u"&t;[%i]&N; %s%s", len(brackets.stack[evt.chan]), url, extra)
			else:
				#rtn.append(u"&t;[%i]&N; %s%s" % (brackets.stack[evt.chan].index(url)+1, url, extra))
				bot.pub_msg(evt, u"&t;[%i]&N; %s%s", brackets.stack[evt.chan].index(url)+1, url, extra)
		else:
			rtn.append(
				"&r;%s&N; %s. %s." % (
				m.group("link"),
				bot._translate(evt, "doesn't exist"),
				bot._translate(evt, "&B;Served in:&N; %s secs") % info['delay'])
			)
			bot.reply(evt, "&r;%s&N; %s. %s." % (
				m.group("link"),
				bot._translate(evt, "doesn't exist"),
				bot._translate(evt, "&B;Served in:&N; %s secs") % info['delay'])
			)
		loop+=1
	#if rtn:
	#	bot.reply(evt, " ".join(rtn))
brackets.rule=re.compile(r"(?:\{\{)([^}[]+)(?:\}\})|(?:\[\[)([^\{\]]+)(?:\]\])")
brackets.thread = True
brackets.fullmsg = True
brackets.stack = {}

def peek(bot, evt, cmd):
	if not cmd.arguments:
		if brackets.stack.has_key(evt.chan):
			if len(brackets.stack[evt.chan]) > 0:
				bot.reply(evt, "since 1 to %i", len(brackets.stack[evt.chan]))
			else:
				bot.reply(evt, "no such data.")
		else:
			bot.reply(evt, "no such data.")
	elif cmd.arguments.isdigit():
		if brackets.stack.has_key(evt.chan) and int(cmd.arguments) <= len(brackets.stack[evt.chan]):
			bot.reply(evt, u"&t;[%i/%i]&N; %s", int(cmd.arguments), len(brackets.stack[evt.chan]), brackets.stack[evt.chan][int(cmd.arguments)-1])
		else:
			bot.reply(evt, "no such data.")
peek.rule ="peek"
peek.aliases = "l"

def prefixes(bot, evt, cmd):
	prefix_list= "!cdefhjlLnprRt"
	pref = cmd.arguments
	if not pref:
		bot.reply(evt, "allowed prefixes for brackets are: %s", ", ".join(["&t;%r&N;" % x for x in prefix_list]))
	elif pref in prefix_list:
		if pref == "!":
			bot.reply(evt, "prefix '&t;!&N;' ignores de next wikilink")
		elif pref == "c":
			bot.reply(evt, "prefix '&t;c&N;' appends '&l;Special:Contributions/&N; if wikilink is a user page'")
		elif pref == "d":
			bot.reply(evt, "prefix '&t;d&N;' appends '&l;?diff=cur&diffonly=1&N;' to the url.")
		elif pref == "e":
			bot.reply(evt, "prefix '&t;e&N;' appends '&l;?action=edit&N;' to the url.")
		elif pref == "h":
			bot.reply(evt, "prefix '&t;h&N;' appends '&l;?action=history&N;' to the url")
		elif pref == "j":
			bot.reply(evt, "prefix '&t;j&N;' appends '&l;?action=raw&ctype=text/javascript&N;'")
		elif pref == "l":
			bot.reply(evt, "prefix '&t;l&N;' appends '&l;?uselang=&N;' (Note: You must specify some language like in l:en[[ko:A]], that returns http://ko.wikipedia.org/wiki/A?uselang=en)")
		elif pref == "L":
			bot.reply(evt, "prefix '&t;L&N;' appends '&l;?diff=cur&N;'")
		elif pref == "n":
			bot.reply(evt, "prefix '&t;n&N;' appends '&l;?redirect=no&N;'")
		elif pref == "p":
			bot.reply(evt, "prefix '&t;p&N;' appends '&l;Special:Prefixindex/&N;'")
		elif pref == "R":
			bot.reply(evt, "prefix '&t;R&N;' appends '&l;?action=render&N;'")
		elif pref == "r":
			bot.reply(evt, "prefix '&t;r&N;' appends '&l;?action=render&diff=cur&diffonly=1&N;'")
		elif pref == "t":
			bot.reply(evt, "prefix '&t;t&N;' shows size info if page exists.")
		elif pref == "":
			bot.reply(evt, "prefix '&t;&N;' appends '&l;&N;'")
		else:
			bot.reply(evt, "No such definition. Please wait to next update :)")
	else:
		bot.reply(evt, "'%s' isn't a prefix for links. Allowed prefixes are: %s", pref, ", ".join(["&t;%r&N;" % x for x in prefix_list]))
prefixes.rule="brackets"
